<template>
  <div style="height: 100%" :key="brder1Key" class="chart" ref="chart"></div>
</template>

<script>
import { mixinReszie } from "@/mixin/resize.js";
import { generateId } from "@/utils";
import { formatDate } from "@/filter/index";
import { LINE_COLOES } from "../../../js/utils";
import { mapGetters } from "vuex";

import { getDeviceAttributes } from "@/api/deviceType";

import { POINT_CHART_TYPES } from "@/utils/local";
import { restSql } from "@/api/taos";
import {
  renderSql,
  setIntervalTime
} from "@/views/centralizedControl/historicalTasksSearch/Curve/js/constent";

export default {
  mixins: [mixinReszie],
  props: {
    row: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    row: {
      handler: async function(newData, oldData) {
        setTimeout(async () => {
          // this.init();
          if (this.row.chargeInTime && this.assignmentToken) {
            await this.getDeviceAttributes();
            this.init();
          }
        }, 500);
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapGetters(["controlDeviceInfo"]),
    attrTokens() {
      return this.attributesList.map(item => item.token);
    },
    chartKeys() {
      return this.controlDeviceInfo._chartKeys;
    },
    // 分配token
    assignmentToken() {
      return this.controlDeviceInfo.assignmentToken;
    },
    // 设备token
    deviceToken() {
      return this.controlDeviceInfo.token;
    },
    tenant() {
      return this.$store.state.user.tenant;
    }
  },
  data() {
    return {
      lineChart: null,
      fullscreen: false,
      brder1Key: generateId(),
      attributesList: [],
      intervalTime: "10s",
      minVal: 0,
      maxVal: 2000
    };
  },
  mounted() {
    // this.init();
  },
  methods: {
    disposeChart() {
      this.brder1Key = generateId();
      this.attributesList = [];
      if (this.lineChart) {
        this.lineChart.dispose();
        this.lineChart = null;
      }
    },
    // 获取点位
    async getDeviceAttributes() {
      console.log("获取点位 :>> ", this.deviceToken);
      return new Promise(async (resolev, reject) => {
        const res = await getDeviceAttributes(
          {
            page: 1,
            pageSize: 1000000
          },
          this.deviceToken
        );
        if (!res.data.results) {
          reject("暂无点位");
        }
        this.attributesList = res.data.results.filter(item => {
          let c = item.isChart.slice(",");
          return c.includes(POINT_CHART_TYPES[0].key);
        });
        resolev();
      });
    },

    getParams() {
      return {
        type: this.attrTokens,
        intervalTime: this.intervalTime,
        deviceEventType: "Measurement"
      };
    },
    // 生成Y轴
    renderyAxis(name, offset = 0) {
      return {
        max: 2000,
        min: 0,
        splitNumber: 20,
        type: "value",
        position: "left",
        offset: offset,
        name,
        axisLabel: {
          color: "#333",
          textStyle: {
            fontSize: 12
          }
        },

        splitLine: {
          //Y轴 分割横线
          show: true,
          lineStyle: {
            color: "#424775",
            width: 0.3
          }
        },
        axisLine: {
          //Y轴 轴线
          show: true
          // lineStyle: {
          //   color: "#fff"
          // }
        },
        axisTick: {
          // show: false,
          lineStyle: {
            color: "#ffffff"
          }
        },
        minorTick: {
          show: false
        },
        minorSplitLine: {
          // 细 分割横线
          show: true,
          lineStyle: {
            color: "#424775",
            width: 0.1
          }
        }
        // axisTick: {
        //   show: false
        // },
        // axisLine: {
        //   show: false
        // }
      };
    },
    async init() {
      let startTime = this.$moment(this.row.chargeInTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      let endTime = this.$moment(this.row.outTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      if (!setIntervalTime({ endDate: endTime, startDate: startTime })) {
        this.$msg("请选择小于一年的时间间隔");
        return;
      }
      this.intervalTime = setIntervalTime({
        endDate: endTime,
        startDate: startTime
      });
      const sqlStr = renderSql({
        ...this.getParams(),
        tenantToken: this.tenant.token,
        assignmentToken: this.assignmentToken,
        endTime,
        startTime
      });
      const results = await restSql(sqlStr);
      const data = results.data;
      const { head } = data;
      const xAxisData = [];
      const yAxisData = [];
      let offset = 0;
      this.attributesList.forEach(item => {
        // 设置y轴 单位
        if (!yAxisData.find(y => y.name == item.unit)) {
          yAxisData.push(this.renderyAxis(item.unit, offset));
          offset += 38;
        }
        // 动态获取头部的下标
        const index = head.findIndex(h => h == item.token.toLowerCase());
        this.$set(item, "dataIndex", index);
        // 添加一个空的放数据的数据
        this.$set(item, "data", []);
      });
      data.data.forEach(d => {
        // x轴
        xAxisData.push(formatDate(d[0]));
        this.attributesList.forEach(item => {
          // 动态获取头部的下标
          item.data.push(d[item.dataIndex]);
        });
      });
      const that = this;
      const series = [];
      console.log("this.attributesList", this.attributesList);
      let minArr = [];
      let maxArr = [];
      this.attributesList.forEach(item => {
        let min = Math.min.apply(null, item.data);
        minArr.push(min);
        let max = Math.max.apply(null, item.data);
        maxArr.push(max);
        series.push({
          name: item.name,
          type: "line",
          smooth: true,
          showSymbol: false,
          data: item.data,
          yAxisIndex: yAxisData.findIndex(y => y.name == item.unit),
          lineStyle: {
            normal: {
              width: 1
            }
          }
        });
      });
      this.minVal = ~~(Math.min.apply(null, minArr) / 100) * 100;
      this.maxVal = Math.ceil(Math.max.apply(null, maxArr) / 100) * 100;
      yAxisData.forEach(res => {
        //  (this.minVal > 200 ? this.minVal - 100 : 0)
        res.min = this.minVal ? this.minVal : 0;
        res.max = this.maxVal ? this.maxVal : 2000;
      });
      console.log("minVal", this.minVal);
      var option = {
        toolbox: {
          right: "5%", //工具栏离容器右侧的距离(left、top、bottom同理)
          top: "4%",
          show: true, //显示区域缩放、缩放还原图标,默认值为true
          feature: {
            dataZoom: {
              yAxisIndex: false //指定哪些Y轴可以被控制（设置为 false，则不控制任何y轴）
            },
            restore: {} //区域缩放重置
          }
        },
        title: {
          text: "实时工艺曲线",
          x: "center",
          // top: "10px",
          textStyle: {
            color: "#333",
            fontSize: 18,
            fontWeight: "400"
          }
        },
        dataZoom: [
          {
            show: true,
            height: 18,
            // xAxisIndex: [0],
            bottom: "2%",
            start: 0,
            end: 100,
            handleIcon:
              "image:// AAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAABZVBMVEUAAAC/zNnCy9jGy9jF zNjFzNjFzdjEzNjEy9jGzNjGzNjGzNjFzNjFzdjEy9jHztjFy9jGxtTFzNvFy9fFzNvFy9bFzNfE zNfGztnFzNjEzdbFzdjFzNjFy9bGzNmq1NTGzdfFzNfD0uHFzNfFzNnBytPEzNnGzdjGzNnEy9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JONDmLHW8VtEaWpGXNqw4GW5iZxK+TQGOB+XboDjeL3l0lkbp45Vvx4fi4ifmcF+KIL 6DfGXoj6dNvrTCQaC9oOFTHCdjAW9eYfUQpfRaU/EKyqtkM14dracE3Irq4KBvyVFar+hj+twqn7 m4nq5AAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMC0wNS0yM1QwNzo1OTozNSswMDowMONkZukAAAAl dEVYdGRhdGU6bW9kaWZ5ADIwMjAtMDUtMjNUMDc6NTk6MzUrMDA6MDCSOd5VAAAAAElFTkSuQmCC",
            handleSize: "110%",
            handleStyle: {
              color: "#CCC"
            },

            textStyle: {
              color: "rgba(170,176,185,1)"
            },
            borderColor: "transparent",
            fillerColor: "#CCC"
          },
          {
            type: "inside",
            show: false,
            height: 20,
            start: 0,
            end: 35
            // minValueSpan: 5
          }
        ],
        color: LINE_COLOES,
        tooltip: {
          trigger: "axis",
          confine: true, //解决浮窗被截断问题 ,把浮窗限制在图标内,不然超出会被遮挡
          show: true,
          formatter: params => {
            var str = "";
            for (var i = 0, l = params.length; i < l; i++) {
              // 小圆点
              const bgStr = `<span style='margin-right: 6px;display:inline-block;width:10px;height:10px;border-radius:10px;background-color:${params[i].color};'></span>`;
              str +=
                bgStr +
                params[i].seriesName +
                ": " +
                params[i].value +
                this.attributesList.find(
                  item => item.name == params[i].seriesName
                )?.unit +
                "<br />";
            }
            return params[0].axisValue + "<br />" + str;
          },
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#E6A23C"
            },
            lineStyle: {
              type: "cross"
            }
          }
        },
        grid: {
          left: "25",
          right: "85",
          bottom: that.fullscreen ? "50" : "34",

          top: "85",
          containLabel: true
        },
        legend: {
          data: this.attributesList.map(item => item.name),
          // padding: [14, 0, 0, 0],
          orient: "horizontal",
          //   icon: "rect",
          show: true,
          textStyle: {
            color: "#333"
          },
          left: 20,
          top: 25
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: xAxisData,
            splitLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              showMaxLabel: true,
              color: "#333",
              // interval: 239,
              textStyle: {
                fontSize: 11
              }
            },
            axisLine: {
              show: false
            }
          },
          {
            type: "value",
            show: true,
            min: 0,
            max: 100,
            axisLabel: {
              show: false
            },
            // 隐藏鼠标进过的显示
            axisPointer: {
              type: "shadow",
              label: {
                show: false
              }
            },
            position: "bottom",
            minorSplitLine: {
              // 细 分割横线
              show: true,
              lineStyle: {
                color: "#424775",
                width: 0.1
              }
            }
          }
        ],
        yAxis: yAxisData,
        series: [...series]
      };
      console.log("option :>> ", option);
      this.$nextTick(() => {
        this.lineChart = this.$echarts.init(this.$refs.chart);

        this.lineChart.setOption(option);

        this.lineChart.on("datazoom", params => {
          //缩放选中的开始时间点数值
          if (params.batch) {
            let startX = params.batch[0].startValue;
            //缩放选中的结束时间点数值
            let endX = params.batch[0].endValue;
            //根据获取的数值从X轴的data中获取对应的时间点
            let startTime = this.lineChart.getOption().xAxis[0].data[startX];
            let endTime = this.lineChart.getOption().xAxis[0].data[endX];
            console.log("object :>> ", startTime, endTime);
          }
        });
      });
    }
  }
};
</script>

<style scoped lang="scss">
.echarts_box {
  .chart {
    width: 100%;
    /* height: 260px; */
  }
}
</style>
